<?php
// +----------------------------------------------------------------------
// | RXThinkCMF敏捷开发框架 [ 赋能开发者，助力企业发展 ]
// +----------------------------------------------------------------------
// | 版权所有 2018~2023 南京RXThinkCMF研发中心
// +----------------------------------------------------------------------
// | Licensed LGPL-3.0 RXThinkCMF并不是自由软件，未经许可禁止去掉相关版权
// +----------------------------------------------------------------------
// | 官方网站: https://www.rxthink.cn
// +----------------------------------------------------------------------
// | Author: @牧羊人 团队荣誉出品
// +----------------------------------------------------------------------
// | 版权和免责声明:
// | 本团队对该软件框架产品拥有知识产权（包括但不限于商标权、专利权、著作权、商业秘密等）
// | 均受到相关法律法规的保护，任何个人、组织和单位不得在未经本团队书面授权的情况下对所授权
// | 软件框架产品本身申请相关的知识产权，禁止用于任何违法、侵害他人合法权益等恶意的行为，禁
// | 止用于任何违反我国法律法规的一切项目研发，任何个人、组织和单位用于项目研发而产生的任何
// | 意外、疏忽、合约毁坏、诽谤、版权或知识产权侵犯及其造成的损失 (包括但不限于直接、间接、
// | 附带或衍生的损失等)，本团队不承担任何法律责任，本软件框架禁止任何单位和个人、组织用于
// | 任何违法、侵害他人合法利益等恶意的行为，如有发现违规、违法的犯罪行为，本团队将无条件配
// | 合公安机关调查取证同时保留一切以法律手段起诉的权利，本软件框架只能用于公司和个人内部的
// | 法律所允许的合法合规的软件产品研发，详细声明内容请阅读《框架免责声明》附件；
// +----------------------------------------------------------------------

namespace app\admin\controller;

use app\admin\model\Task;
use app\admin\model\Clss;
use app\admin\model\Project;
use app\admin\service\TaskscoreRecordService;

/**
 * 体测记录管理-控制器
 * @author 牧羊人
 * @since: 2023/08/24
 * Class TaskscoreRecord
 * @package app\admin\controller
 */
class TaskscoreRecord extends Backend
{
    /**
     * 初始化方法
     * @author 牧羊人
     * @since: 2023/08/24
     */
    public function initialize()
    {
        parent::initialize(); // TODO: Change the autogenerated stub
        $this->model = new \app\admin\model\TaskscoreRecord();
        $this->service = new TaskscoreRecordService();
    }

    /**
     * 导出Excel
     * @throws \PHPExcel_Exception
     * @throws \PHPExcel_Reader_Exception
     * @throws \PHPExcel_Writer_Exception
     * @since 2021/3/25
     * @author 牧羊人
     */
    public function exportExcel()
    {
        /**
         * 性别
         */
        $gender_list = [
            1 => '男',
            2 => '女',
            3 => '未知',
        ];

        /**
         * 模式
         */
        $mode_list = [
            1 => '测试模式',
            2 => '锻炼模式',
            3 => '体育赛事',
        ];

        /**
         * 评定
         */
        $rating_list = [
            0 => '不及格',
            1 => '优秀',
            2 => '良好',
            3 => '及格',

        ];

        $param = request()->param();

        // 查询条件
        $map = [];
        $taskId = isset($param['taskId']) ? (int)$param['taskId'] : 0;
        if ($taskId) {
            $map[] = ['taskId', '=', $taskId];
        }
        // 所在院系
        $departmentsId = isset($param['departmentsId']) ? (int)$param['departmentsId'] : 0;
        if ($departmentsId) {
            $map[] = ['departmentsId', '=', $departmentsId];
        }

        // schoolId
        $schoolId = isset($param['schoolId']) ? (int)$param['schoolId'] : 0;
        if ($schoolId) {
            $map[] = ['schoolId', '=', $schoolId];
        }

        // gradeId
        $gradeId = isset($param['gradeId']) ? (int)$param['gradeId'] : 0;
        if ($gradeId) {
            $map[] = ['gradeId', '=', $gradeId];
        }

        // classId
        $classId = isset($param['classId']) ? (int)$param['classId'] : 0;
        if ($classId) {
            $map[] = ['classId', '=', $classId];
        }

        // professionalId
        $professionalId = isset($param['professionalId']) ? (int)$param['professionalId'] : 0;
        if ($professionalId) {
            $map[] = ['professionalId', '=', $professionalId];
        }

        // projectId
        $projectId = isset($param['projectId']) ? (int)$param['projectId'] : 0;
        if ($projectId) {
            $map[] = ['projectId', '=', $projectId];
        }

        // taskId
        $taskId = isset($param['taskId']) ? (int)$param['taskId'] : 0;
        if ($taskId) {
            $map[] = ['taskId', '=', $taskId];
        }

        // keywords
        $keywords = isset($param['keywords']) ? (string)$param['keywords'] : '';
        if ($keywords) {
            $map[] = ['testerName|testerNumber', 'like', "%{$keywords}%"];
        }

        // gender
        $gender = isset($param['gender']) ? (string)$param['gender'] : 0;
        if ($gender) {
            $map[] = ['gender', '=', $gender];
        }

        // mode
        $mode = isset($param['mode']) ? (string)$param['mode'] : 0;
        if ($mode) {
            $map[] = ['type', '=', $mode];
        }

        if ($taskId) {
            $ds = 'pingscore desc,score desc';
            $fs = 'MAX(score) as score';
            $map[] = ['taskId', '=', $taskId];
            $tiyuclass = json_decode(Task::where('id',$taskId)->value('class'),true);
            $map[] = ['tiyu_class', '=', intval($tiyuclass[0])];

            $project = Task::where('id',$taskId)->value('project');
            $code = Project::where('id',$project)->value('code');

            $btype = Project::where('id',$project)->value('btype');
            if ($btype==2) {
                $ds = 'pingscore desc,score asc';
                $fs = 'MAX(score) as score';
            }
            if ($code=='BMI') {
                $map[] = ['bmi', '<>', ''];
                $ds = 'pingscore desc,bmi asc';
            }
        }

        // 排序
        $sort = isset($param['sort']) && $param['order'] ? $param['sort'] . ' ' . $param['order'] : $ds;

        // 获取导出的数据源
        $result = $this->model->where($map)->order($sort)->group('memberId')->field($fs)->column("id");

        $list = [];
        if (is_array($result)) {
            foreach ($result as $val) {
                $info = $this->model->getInfo($val);
                $list[] = $info;
            }
        }

        // 实例化PHPExcel类
        $objPHPExcel = new \PHPExcel();
        // 激活当前的sheet表
        $objPHPExcel->setActiveSheetIndex(0);
        //5.设置表格头（即excel表格的第一行）
        $objPHPExcel->setActiveSheetIndex(0)
            ->setCellValue('A1', '项目')
            ->setCellValue('B1', '任务名称')
            ->setCellValue('C1', '模式')
            ->setCellValue('D1', '姓名')
            ->setCellValue('E1', '学籍号')
            ->setCellValue('F1', '性别')
            ->setCellValue('G1', '学校')
            ->setCellValue('H1', '年级')
            ->setCellValue('I1', '专业')
            ->setCellValue('J1', '体育班级')
            ->setCellValue('K1', '运动成绩')
            ->setCellValue('L1', '运动耗时')
            ->setCellValue('M1', 'bmi')
            ->setCellValue('N1', '评分')
            ->setCellValue('O1', '评定')
            ->setCellValue('P1', '运动时间');
        // 设置表格头水平居中
        $objPHPExcel->setActiveSheetIndex(0)->getStyle('A1')->getAlignment()
            ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->setActiveSheetIndex(0)->getStyle('B1')->getAlignment()
            ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->setActiveSheetIndex(0)->getStyle('C1')->getAlignment()
            ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->setActiveSheetIndex(0)->getStyle('D1')->getAlignment()
            ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->setActiveSheetIndex(0)->getStyle('E1')->getAlignment()
            ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->setActiveSheetIndex(0)->getStyle('F1')->getAlignment()
            ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->setActiveSheetIndex(0)->getStyle('G1')->getAlignment()
            ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->setActiveSheetIndex(0)->getStyle('H1')->getAlignment()
            ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->setActiveSheetIndex(0)->getStyle('I1')->getAlignment()
            ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->setActiveSheetIndex(0)->getStyle('J1')->getAlignment()
            ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->setActiveSheetIndex(0)->getStyle('K1')->getAlignment()
            ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->setActiveSheetIndex(0)->getStyle('L1')->getAlignment()
            ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->setActiveSheetIndex(0)->getStyle('M1')->getAlignment()
            ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->setActiveSheetIndex(0)->getStyle('N1')->getAlignment()
            ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->setActiveSheetIndex(0)->getStyle('O1')->getAlignment()
            ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->setActiveSheetIndex(0)->getStyle('P1')->getAlignment()
            ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        //设置列水平居中
        $objPHPExcel->setActiveSheetIndex(0)->getStyle('A')->getAlignment()
            ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->setActiveSheetIndex(0)->getStyle('B')->getAlignment()
            ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->setActiveSheetIndex(0)->getStyle('C')->getAlignment()
            ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->setActiveSheetIndex(0)->getStyle('D')->getAlignment()
            ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->setActiveSheetIndex(0)->getStyle('E')->getAlignment()
            ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->setActiveSheetIndex(0)->getStyle('F')->getAlignment()
            ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->setActiveSheetIndex(0)->getStyle('G')->getAlignment()
            ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->setActiveSheetIndex(0)->getStyle('H')->getAlignment()
            ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->setActiveSheetIndex(0)->getStyle('I')->getAlignment()
            ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->setActiveSheetIndex(0)->getStyle('J')->getAlignment()
            ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->setActiveSheetIndex(0)->getStyle('K')->getAlignment()
            ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->setActiveSheetIndex(0)->getStyle('L')->getAlignment()
            ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->setActiveSheetIndex(0)->getStyle('M')->getAlignment()
            ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->setActiveSheetIndex(0)->getStyle('N')->getAlignment()
            ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->setActiveSheetIndex(0)->getStyle('O')->getAlignment()
            ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->setActiveSheetIndex(0)->getStyle('P')->getAlignment()
            ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        // 设置单元格宽度
        $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('A')->setWidth(10);
        $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('B')->setWidth(10);
        $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('C')->setWidth(10);
        $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('D')->setWidth(10);
        $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('E')->setWidth(10);
        $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('F')->setWidth(10);
        $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('G')->setWidth(10);
        $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('H')->setWidth(10);
        $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('I')->setWidth(10);
        $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('J')->setWidth(10);
        $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('K')->setWidth(10);
        $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('L')->setWidth(10);
        $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('M')->setWidth(10);
        $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('N')->setWidth(10);
        $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('O')->setWidth(10);
        $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('P')->setWidth(10);
        // 循环刚取出来的数组，将数据逐一添加到excel表格。
        for ($i = 0; $i < count($list); $i++) {
            $objPHPExcel->getActiveSheet()->setCellValue('A' . ($i + 2), $list[$i]['project']);// 项目
            $objPHPExcel->getActiveSheet()->setCellValue('B' . ($i + 2), $list[$i]['task']);// 任务名称
            $objPHPExcel->getActiveSheet()->setCellValue('C' . ($i + 2), $mode_list[$list[$i]['type']]);// 模式
            $objPHPExcel->getActiveSheet()->setCellValue('D' . ($i + 2), $list[$i]['testerName']);// 姓名
            $objPHPExcel->getActiveSheet()->setCellValue('E' . ($i + 2), $list[$i]['testerNumber']);// 学籍号
            $objPHPExcel->getActiveSheet()->setCellValue('F' . ($i + 2), $gender_list[$list[$i]['gender']]);// 性别
            $objPHPExcel->getActiveSheet()->setCellValue('G' . ($i + 2), $list[$i]['school']);// 学校
            $objPHPExcel->getActiveSheet()->setCellValue('H' . ($i + 2), $list[$i]['grade']);// 年级
            $objPHPExcel->getActiveSheet()->setCellValue('I' . ($i + 2), $list[$i]['professional']);// 专业
            $objPHPExcel->getActiveSheet()->setCellValue('J' . ($i + 2), Clss::where('id',$list[$i]['tiyu_class'])->value('name'));// 体育班级
            $objPHPExcel->getActiveSheet()->setCellValue('K' . ($i + 2), isset($list[$i]['score'])?$list[$i]['score']:$list[$i]['score']);// 运动成绩
            $objPHPExcel->getActiveSheet()->setCellValue('L' . ($i + 2), $list[$i]['duration']);// 运动耗时
            $objPHPExcel->getActiveSheet()->setCellValue('M' . ($i + 2), $list[$i]['bmi']);// bmi
            $objPHPExcel->getActiveSheet()->setCellValue('N' . ($i + 2), $list[$i]['pingscore']);// 评分
            $objPHPExcel->getActiveSheet()->setCellValue('O' . ($i + 2), isset($list[$i]['ratingStr'])?$list[$i]['ratingStr']:'');// 评定
            $objPHPExcel->getActiveSheet()->setCellValue('P' . ($i + 2), $list[$i]['createdDate']);// 运动时间
        }
        // 设置保存的Excel表格名称
        $filename = '任务成绩_' . date('YmdHis', time()) . ".xlsx";
        // 设置当前激活的sheet表格名称
        $objPHPExcel->getActiveSheet()->setTitle('任务成绩');

        // 保存本地文件
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
        try {
            // 保存文件
            $objWriter->save(UPLOAD_TEMP_PATH . "/" . $filename);
            return download(UPLOAD_TEMP_PATH . "/" . $filename, $filename);
        } catch (Exception $e) {
            echo "文件保存失败：" . $e->getMessage();
        }

        // 文件地址
//        $filePath = get_image_url('/uploads'.str_replace(ATTACHMENT_PATH, "", UPLOAD_TEMP_PATH . "/" . $filename));
//        return $this->jsonReturn(message("操作成功", true, $filePath));
    }


}